import { _decorator, Component, KeyCode, Label, math, Sprite, Vec2, Vec3 } from "cc";
import { gameMain } from "../../../GameMain";
import { keyMgr } from "../../com/KeyMgr";
import { MsgVo } from "../../cfg/Msg";
import { playerMod } from "./PlayerMod";
const { ccclass, property } = _decorator;

@ccclass("Player")
export class Player extends Component {

    @property(Sprite)
    body: Sprite
    @property(Label)
    labName: Label

    isMe = false;

    toVec3: Vec3 = new Vec3();
    toAng: number;

    onCreate(data: MsgVo.com.Player) {
        let isMe = this.isMe = data.pid === playerMod.pid;
        this.body.color = isMe ? math.color("#00ff00") : math.color("#ff0000");
        this.labName.string = data.name;
        this.node.setPosition(data.x, data.y);
        this.body.node.angle = data.ang - 90;
        this.toVec3.set(this.node.position);
        this.toAng = this.body.node.angle;
    }

    sendDt = 0;
    update(dt: number) {
        if (this.isMe) {
            gameMain.focus = this.node;
            let { x, y } = this.node.position;
            let oldX = x;
            let oldY = y;
            let spd = 128;
            let change = false;
            if (keyMgr.isKeyDown(KeyCode.KEY_W)) {
                y += dt * spd;
                change = true;
            }
            if (keyMgr.isKeyDown(KeyCode.KEY_S)) {
                y -= dt * spd;
                change = true;
            }
            if (keyMgr.isKeyDown(KeyCode.KEY_A)) {
                x -= dt * spd;
                change = true;
            }
            if (keyMgr.isKeyDown(KeyCode.KEY_D)) {
                x += dt * spd;
                change = true;
            }
            if (change) {
                this.body.node.angle = math.toDegree(Math.atan2(y - oldY, x - oldX)) - 90;
            }
            this.node.setPosition(x, y);
            this.sendDt += dt;
            if (this.sendDt > 1 / 20) {
                if (change) {
                    this.sendDt = 0;
                    playerMod.syncPlayer(this.node.position.x, this.node.position.y);
                }
            }

            this.toVec3.set(this.node.position);
            this.toAng = this.body.node.angle;
        }
        this.node.setPosition(new Vec3(this.node.position).lerp(this.toVec3, dt * 8));
        this.body.node.angle = math.lerp(this.body.node.angle, this.toAng, dt * 8);
    }

}